# query_example.py
# usage: 根据问题返回案例提示词
# python ./src/query/query_example.py --query "请问2024年1月公卫医疗专题各区县按时回复率分别是多少？"

import os,sys
# 添加项目根目录到路径
project_root = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
sys.path.insert(0, project_root)

import argparse
import json
from typing import Optional, Dict
from tools.clean_question import clean_question


def query_example(question: str) -> Optional[str]:
    """
    根据输入问题，返回参考问题和SQL的拼接字符串。

    :param question: 用户输入的问题
    :return: 匹配结果字符串，格式为 "参考问题{question} , 参考SQL结果{sql}"，未找到返回 None
    """
    # 清洗问题，获取 template
    try:
        template = clean_question(question)
    except Exception as e:
        print(f"[Error] clean_question failed: {e}")
        return None

    # 逐行读取 JSON Lines 文件，查找 template 严格匹配的记录
    try:
        with open("tmp_template2sql.json", 'r', encoding='utf-8') as f:
            for line in f:
                line = line.strip()
                if not line:
                    continue
                try:
                    record = json.loads(line)
                    if record.get("template") == template:
                        matched_question = record.get("question", "")
                        sql = record.get("sql", "")
                        return f"参考案例：{matched_question} , 输出的SQL为 {sql}"
                except json.JSONDecodeError:
                    continue  # 跳过无效 JSON 行
    except Exception as e:
        print(f"[Error] Failed to read template file: {e}")
        return None

    return None  


def main():
    parser = argparse.ArgumentParser(description="根据问题查找匹配的参考SQL")
    parser.add_argument('--query', type=str, required=True, help='输入的问题')
    args = parser.parse_args()

    result = query_example(args.query)
    if result:
        print(result)
    else:
        print("未找到匹配的模板记录。", end="")


if __name__ == '__main__':
    main()